/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.web;

import javax.servlet.ServletContext;

import net.sourceforge.wurfl.core.CustomWURFLHolder;
import net.sourceforge.wurfl.core.WURFLHolder;
import net.sourceforge.wurfl.core.WURFLManager;
import net.sourceforge.wurfl.core.WURFLUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;

/**
 * ServletContext WURFLHolder decorator.
 * 
 * <p>
 * This class is used to instantiate a WURFLHolder into web application. It is a
 * WURFLHolder Decorator build the delegate by the ServletContext parameters.
 * </p>
 * 
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: ServletContextWURFLHolder.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class ServletContextWURFLHolder implements WURFLHolder {

	/** ServletContext wurfl main file parameter */
	public static final String WURFL = "wurfl";

	/** ServletContext wurfl patch files parameter */
	public static final String WURFL_PATCH = "wurflPatch";

	/** WURFLHolder delegate */
	private WURFLHolder delegate;

	/**
	 * Build a ServletContextHolder by containing ServletContext.
	 * 
	 * @param servletContext
	 */
	public ServletContextWURFLHolder(ServletContext servletContext) {

		delegate = createDelegate(servletContext);
	}

	// Factory methods ****************************************************

	/**
	 * Create WURFLHolder delegate from servlet context.
	 * 
	 * @param servletContext
	 *            The ServletContext used to init this WURFLHolder.
	 * @return delegate tuWURFLHolder instance.
	 */
	private WURFLHolder createDelegate(ServletContext servletContext) {

		// main file
		String mainPath = servletContext.getInitParameter(WURFL);
		Validate.notEmpty(mainPath, "Please Specify a Valid Location for "
				+ WURFL + " context parameter");

		String rootPath = servletContext.getRealPath(mainPath);
		String[] patchesPath = StringUtils.split(StringUtils.defaultString(
				servletContext.getInitParameter(WURFL_PATCH)), " ,");
		for (int index = 0; index < patchesPath.length; index++) {
			patchesPath[index] = servletContext.getRealPath(patchesPath[index]);
		}

		WURFLHolder wurflHolder = new CustomWURFLHolder(rootPath, patchesPath);

		return wurflHolder;
	}

	// WURFLHolder implementation *****************************************

	/**
	 * {@inheritDoc}
	 */
	public WURFLManager getWURFLManager() {

		return delegate.getWURFLManager();
	}

	/**
	 * {@inheritDoc}
	 */
	public WURFLUtils getWURFLUtils() {

		return delegate.getWURFLUtils();
	}

}
